package com.example.contentprovidermodule

import android.content.ContentProvider
import android.content.ContentUris
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import android.util.Log

class PersonProvider:ContentProvider() {
    private val TAG = "PersonProvider"
    private var dbHelper:DBHelper?=null
    private val uriMatcher by lazy {
        val matcher = UriMatcher(UriMatcher.NO_MATCH)
        matcher.addURI("com.example.contentprovidermodule.provider","myprovider",1)
        matcher.addURI("com.example.contentprovidermodule.provider","myprovider/#",2)
        matcher
    }
    
    init {
        Log.d(TAG, "Provider开始创建 ")
         }
    override fun onCreate()=context?.let {
        this.dbHelper=DBHelper(it)
        true
    }?:false

    override fun query(uri: Uri, projection: Array<out String>?,
                       selection: String?, selectionArgs: Array<out String>?,
                       sortOrder: String?)=dbHelper?.let {
        Log.d(TAG, "query: ")
        val db = it.readableDatabase
        val cursor= when(this.uriMatcher.match(uri)){
            1->{
                 db.query("myprovider", projection, selection, selectionArgs,null,null,sortOrder)
            }
            2->{
                val s = uri.pathSegments[1]
                db.query("myprovider",projection,"id = ?", arrayOf(s),null,null,sortOrder)
            }
            else->throw RuntimeException("查询不合法")
        }
        cursor
    }


    override fun getType(uri: Uri): String? {
//        TODO("Not yet implemented")
        Log.d(TAG, "getType: ")
        return null
    }

    override fun insert(uri: Uri, values: ContentValues?)=dbHelper?.let {
        val readableDatabase = it.readableDatabase
        Log.d(TAG, "insert: ")
        val insert = readableDatabase.insert("myprovider", null, values)
        Log.d(TAG, "insert: ")
        Log.d(TAG, "insert: =$insert")
        val urii=ContentUris.withAppendedId(uri,insert)
        urii
    }

    override fun delete(uri: Uri, selection: String?, selectionArgs: Array<out String>?): Int {
//        TODO("Not yet implemented")
        Log.d(TAG, "delete: ")
        return 0
    }
    

    override fun update(uri: Uri, values: ContentValues?, selection: String?, selectionArgs: Array<out String>?): Int {
//        TODO("Not yet implemented")
        Log.d(TAG, "update: ")
        return 0
    }
}